package com.example.kotlinlearn

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import kotlin.math.log

open class BaseActivity: AppCompatActivity() {

    lateinit var unLoginBroadcastReceiver :UnLoginBroadcastReceiver

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        //打印当前实例的类名
        Log.d("BaseActivity", javaClass.simpleName)
        //将下面的子类全部加入到活动管理单例类中
        ActivityCollector.addActivity(this)
    }

    override fun onResume() {
        super.onResume()
        //打印当前实例的类名
        Log.d("BaseActivity", javaClass.simpleName)
        //在活动创建时注册广播接收器
        val intentFilter = IntentFilter()
        intentFilter.addAction("com.example.bim.UnLogin")
        unLoginBroadcastReceiver = UnLoginBroadcastReceiver()
        registerReceiver(unLoginBroadcastReceiver,intentFilter)
    }

    override fun onPause() {
        super.onPause()
        //在活动暂停时停止接收广播
        unregisterReceiver(unLoginBroadcastReceiver)
    }

    /**
     * 在活动被销毁时，将其从现存的活动列表中删除
     */
    override fun onDestroy() {
        super.onDestroy()
        ActivityCollector.removeActivity(this)
    }

    inner class UnLoginBroadcastReceiver:BroadcastReceiver(){
        override fun onReceive(context: Context?, intent: Intent?) {
            if (context != null) {
                AlertDialog.Builder(context).apply {
                    setTitle("强制下线")
                    setMessage("该账号已在别处登陆，请重新登陆")
                    setPositiveButton("确认"){
                            _, _ ->ActivityCollector.finishAll()
                        val intent = Intent(context,MainActivity::class.java)
                        context.startActivity(intent)
                    }
                    show()
                }
            }
        }
    }
}